var video = document.querySelector('video');
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
var exArray = []; //存储设备源ID
navigator.mediaDevices.enumerateDevices()
	.then(function (devices) {
		devices.forEach(function (device) {
			if (device.kind == "videoinput") {
				exArray.push(device.deviceId);
			}
		});

	})
	.catch(function (err) {
		alert(err.name + ": " + err.message);
	});




// $(".fchangeCam").click(function () {
// 	getMedia(0);
// })
// $(".lchangeCam").click(function () {
// 	getMedia(1);
// })

$(".fchangeCam")[0].addEventListener("click", function(){
    getMedia(0);
});

$(".lchangeCam")[0].addEventListener("click", function(){
    getMedia(1);
});

function getMedia(a) {
	if (navigator.getUserMedia) {
		navigator.getUserMedia({
			'video': {
				'optional': [{
					'sourceId': exArray[a] //0为前置摄像头，1为后置
				}]
			},
			'audio': true
		}, successFunc, errorFunc); //success是获取成功的回调函数
	} else {
		alert('Native device media streaming (getUserMedia) not supported in this browser.');
	}
}

function successFunc(stream) {
	//alert('Succeed to get media!');
	if (video.mozSrcObject !== undefined) {
		//Firefox中，video.mozSrcObject最初为null，而不是未定义的，我们可以靠这个来检测Firefox的支持
		video.mozSrcObject = stream;
	} else {
		video.src = window.URL && window.URL.createObjectURL(stream) || stream;
	}

	video.play();

}

function errorFunc(e) {
	alert('Error！' + e);
}

//拍照
function getPhoto() {
	context1.drawImage(video, 0, 0, 90, 120); //将video对象内指定的区域捕捉绘制到画布上指定的区域，实现拍照。
}
